package hanelsoft.vn.dictionaylearn;

import hanelsoft.vn.dictionaylearn.control.activity.ContentView;
import hanelsoft.vn.dictionaylearn.control.activity.History;
import hanelsoft.vn.dictionaylearn.control.activity.Setting;
import hanelsoft.vn.dictionaylearn.control.activity.Vocabulary;
import hanelsoft.vn.dictionaylearn.control.custom.CustomListHomeActivity;
import hanelsoft.vn.dictionaylearn.model.common.Utility;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFile;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFileList;
import hanelsoft.vn.dictionaylearn.model.db.VocabularySQLiteHelper;
import hanelsoft.vn.dictionaylearn.model.entity.InfoListHomeActivity;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabulary;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabularyContent;

import java.io.File;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class ActivityHome extends Activity {
	Button vocadict_btn_back, vocadict_btn_go;
	ImageButton btnTurnOff, vocadict_btn_add;
	TextView vocadict_show_dictionary;
	EditText vocadict_edit_search;
	ListView vocadict_list;
	static final private String MAIN_TAG = "[ActivityHome]";
	static final private int VIEW_RADIO_ID = 12100702;
	private String mDBExtension;
	private String mDBPath;
	private SharedPreferences prefs;
	private int mWaitingTime;
	private Handler mHandler;
    private Runnable mUpdateTimeTask;
    private InputMethodManager imm;
	private DatabaseFileList mDBList;
	private DatabaseFile mDBFile;
	public ArrayList<String> mLSTCurrentWord = null;
	public ArrayList<Integer> mLSTCurrentWordId = null;
    ArrayList<InfoListHomeActivity> arraylist;
    VocabularySQLiteHelper mVocabularySQLiteHelper = new VocabularySQLiteHelper(this);
    InfoVocabulary infoGetVocabulary;
    ArrayList<InfoVocabulary> arrayVocabulary;
    Cursor result;
    @TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint("NewApi") @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // requestWindowFeature(Window.FEATURE_NO_TITLE);
        imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        //Check SdCard
        File patch = Environment.getExternalStorageDirectory();
        File pathInternal = Environment.getDataDirectory();
        if(Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9)
        {
        	Log.i(MAIN_TAG, "SDK: "+Integer.valueOf(android.os.Build.VERSION.SDK_INT));
        	long total = patch.getTotalSpace();
            Log.i(MAIN_TAG, "Total size: "+total);
            long used = patch.getUsableSpace();
            Log.i(MAIN_TAG, "used size: "+used);
            long freespace = patch.getFreeSpace();
            Log.i(MAIN_TAG, "freespace size: "+freespace);
            //
            long totalInternal = pathInternal.getTotalSpace();
            Log.i(MAIN_TAG, "Total size: "+totalInternal);
            long usedInternal = pathInternal.getUsableSpace();
            Log.i(MAIN_TAG, "used size: "+usedInternal);
            long freespaceInternal = pathInternal.getFreeSpace();
            Log.i(MAIN_TAG, "freespace size: "+freespaceInternal);
        }
        String link = patch.getPath();
        Log.i(MAIN_TAG, "link: "+link);
        String name = patch.getName();
        Log.i(MAIN_TAG, "name: "+name);
        //
        String linkInternal = pathInternal.getPath();
        Log.i(MAIN_TAG, "linkInternal: "+linkInternal);
        String nameInternal = pathInternal.getName();
        Log.i(MAIN_TAG, "nameInternal: "+nameInternal);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        	Log.i(MAIN_TAG, "SDCard is mounted");
        	mDBPath = getResources().getString(R.string.dbPath);
        }
        else
        {
        	Log.i(MAIN_TAG, "SDCard is unmounted");
        	mDBPath = getResources().getString(R.string.dbPathNotSDCard);
        }
        //get position data dictionary
        mDBExtension = getResources().getString(R.string.dbExtension);
        mDBPath = getResources().getString(R.string.dbPath);
        mDBList = new DatabaseFileList(mDBPath,mDBExtension);
        //
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        mWaitingTime = Integer.parseInt(prefs.getString("waitingTime", "1"));
        //load data
        loadPreferences();
        setContentView(R.layout.activity_home);
        if (mDBList.items.size() > 0)
        {
            menuMain();
        }
        else
        {
			new AlertDialog.Builder(this)
			.setMessage(R.string.errorNoData)
			.setTitle(getString(R.string.error))
			.setNeutralButton(getString(R.string.ok),
			   new DialogInterface.OnClickListener() {
			   public void onClick(DialogInterface dialog, int whichButton){}
			   })
			.show();        
        }
    }
    
    public void loadPreferences()
	{
    	Log.i(MAIN_TAG, "Start loadPreferences");
		boolean found = false;
		String savedDB = prefs.getString("defaultDictionary", ""); //Default dictionary is the first dictionary in the list
		String savedDBPath = prefs.getString("defaultDictionaryPath", ""); //Default dictionary is the first dictionary in the list
		if (savedDB.trim().equals("") || savedDBPath.trim().equals(""))
		{
			if (mDBList != null && mDBList.items.size() > 0)
			{
				mDBFile = mDBList.items.get(0);
			}
			else
			{
				mDBFile = null;
			}
		}
		else
		{
			if (mDBList != null && mDBList.items.size() > 0)
			{
				for (DatabaseFile d : mDBList.items)
				{
					if (d.fileName.equals(savedDB) && d.path.equals(savedDBPath))
					{
						mDBFile = d;
						found = true;
						break;
					}
				}
				if (!found)
				{
					mDBFile = mDBList.items.get(0);
				}
			}
			else
			{
				Log.d(MAIN_TAG,"No database found");
				mDBFile = null;
			}
		}
		if (mDBFile != null)
		{
			Log.d(MAIN_TAG,"default path = " + mDBFile.path + " | filename = " + mDBFile.fileName);
		}
		else
		{
			Log.i(MAIN_TAG,"No database found!");
		}
	}
	@SuppressWarnings("deprecation")
	private void showDictionary()
    {
		Log.i(MAIN_TAG, "Start showDictionary");
    	LayoutInflater factory = LayoutInflater.from(this);
    	View view = factory.inflate(R.layout.dictionary_show, null);
    	ScrollView mScrollView = (ScrollView)view.findViewById(R.id.dictionary_show_dictionary);
    	final RadioGroup mRadioGroup = new RadioGroup(this);
    	mRadioGroup.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.FILL_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT));
    	mRadioGroup.setOrientation(RadioGroup.VERTICAL);
    	//
    	for(int i=0; i<mDBList.items.size(); i++)
    	{
    		RadioButton mRadioButton = new RadioButton(this);
    		mRadioButton.setId(VIEW_RADIO_ID + i);
    		mRadioButton.setText(mDBList.items.get(i).dictionaryName);
    		mRadioButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    		mRadioGroup.addView(mRadioButton, i);
    		if (mDBFile != null && mDBFile.fileName.equals(mDBList.items.get(i).fileName))
            {
            	mRadioGroup.check(VIEW_RADIO_ID + i);
            }
    	}
    	mScrollView.addView(mRadioGroup);
    	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    	alertDialogBuilder.setView(view);
    	alertDialogBuilder.setTitle(R.string.dictionary_management);
    	alertDialogBuilder.setIcon(R.drawable.icon);
    	alertDialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        }).setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            	//setContentView(R.layout.main);
        		int selectedIndex = mRadioGroup.getCheckedRadioButtonId();
        		if (selectedIndex < 0)
        		{
        			selectedIndex = 0;
        		}
        		mDBFile = mDBList.items.get(selectedIndex - VIEW_RADIO_ID);
        		savePreferences();
        		menuMain();
            }
        });
    	Dialog dialog = alertDialogBuilder.create();
        dialog.show();
    }
    public void savePreferences()
	{
       	SharedPreferences.Editor editor = prefs.edit();
       	editor.putString("defaultDictionary", mDBFile.fileName);
       	editor.putString("defaultDictionaryPath", mDBFile.path);
		editor.commit();
	}
	public void showWordlist()
    {
		Log.i(MAIN_TAG, "Start showWordList");
		arraylist = new ArrayList<InfoListHomeActivity>();
		ArrayList<String> array = new ArrayList<String>();
		vocadict_edit_search.setEnabled(false);
		String word = vocadict_edit_search.getText().toString();
		Uri uri = Uri.parse("content://hanelsoft.vn.dictionaylearn.model.common.VocadictProvider/dict/" + mDBFile.fileName + "/list/" + word);
		try
		{
			//result = managedQuery(uri,null,null,null,null);
			result = getContentResolver().query(uri, null, null, null, null);
	        if (result != null)
	        {
	        	int countRow=result.getCount();
	    		Log.i(MAIN_TAG, "countRow = " + countRow);
	    		mLSTCurrentWord.clear();
	    		Log.i(MAIN_TAG, "countRow2 = " + countRow);
	    		mLSTCurrentWordId.clear();
	    		Log.i(MAIN_TAG, "countRow3 = " + countRow);
	    		//mAdapter.clear();
	    		Log.i(MAIN_TAG, "countRow4 = " + countRow);
	        	if (countRow >= 1)
	        	{
	        		Log.i(MAIN_TAG, "countRow >= 1");
	        	   	int indexWordColumn = result.getColumnIndex("word");
	        	   	int indexIdColumn = result.getColumnIndex("id");
	                result.moveToFirst();
	        		String strWord;
	        		int intId;
	        		int i = 0;
	                do
	                {
	                	Log.i(MAIN_TAG, "do "+i);
	                	strWord = Utility.decodeContent(result.getString(indexWordColumn));
	                	intId = result.getInt(indexIdColumn);
	                    mLSTCurrentWord.add(i,strWord);
	                    mLSTCurrentWordId.add(i,intId);
	                    Log.i(MAIN_TAG, "do2 "+i);
	                    InfoListHomeActivity info;
	                    info = new InfoListHomeActivity(strWord);
	                    arraylist.add(info);
	                    //mAdapter.add(strWord);
	                    array.add(strWord);
	                    i++;
	                } while (result.moveToNext()); 
	            }
	        }
			//assign result return
	        Log.i(MAIN_TAG, "set adapter");
	        vocadict_list.setAdapter(new CustomListHomeActivity(ActivityHome.this, arraylist));
		}
		catch (Exception ex)
		{
			Log.e(MAIN_TAG, "Error = " + ex.toString());
		}
		vocadict_edit_search.setEnabled(true);
		Log.i(MAIN_TAG, "finish vocadict_edit_search.setEnabled(true)");
    }
    public void menuMain()
    {
    	Log.i(MAIN_TAG, "Start menuMain");
    	 //
        vocadict_btn_go = (Button)findViewById(R.id.vocadict_btn_go);
        btnTurnOff = (ImageButton)findViewById(R.id.vocadict_cancel);
        vocadict_btn_add = (ImageButton)findViewById(R.id.vocadict_btn_add);
        vocadict_show_dictionary = (TextView)findViewById(R.id.vocadict_show_dictionary);
        vocadict_edit_search = (EditText)findViewById(R.id.vocadict_edit_search);
        vocadict_list = (ListView)findViewById(R.id.vocadict_list);
        //keyboar actionSearch
        vocadict_edit_search.setOnEditorActionListener(new OnEditorActionListener(){  

            @Override 
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) { 
                if(arg1 == EditorInfo.IME_ACTION_SEARCH)  
                { 
                	if(vocadict_edit_search.getText().toString().trim().equals(""))
    				{
    					
    				}
    				else
    				{
	                	imm.hideSoftInputFromWindow(vocadict_edit_search.getWindowToken(), 0);
			    		Intent i = new Intent(ActivityHome.this, ContentView.class);
			    		i.putExtra("word", vocadict_edit_search.getText().toString());
			    		i.putExtra("db", mDBFile.fileName);
			    		i.putExtra("dbName",mDBFile.dictionaryName);
			    		i.putExtra("style", mDBFile.style);
			    		i.putExtra("sourcesound", mDBFile.sourceLanguage);
			            startActivity(i);
    				}
                }
                return false; 
            } 
        }); 
        //turn off
        btnTurnOff.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater mLayoutInflater = LayoutInflater.from(ActivityHome.this);
				View mView = mLayoutInflater.inflate(R.layout.vocabulary_shutdown, null);
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityHome.this);
		    	alertDialogBuilder.setView(mView);
		    	alertDialogBuilder.setTitle(R.string.shut_down);
		    	alertDialogBuilder.setIcon(R.drawable.exit);
		    	alertDialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
		            @Override
		            public void onCancel(DialogInterface dialog) {
		                finish();
		            }
		        }).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
		            public void onClick(DialogInterface dialog, int which) {
						finish();
		            }
		        }).setNegativeButton(R.string.cancel,new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				});
		    	Dialog dialog = alertDialogBuilder.create();
		        dialog.show();
			}
		});
        //
    	mLSTCurrentWordId = new ArrayList<Integer>();
    	mLSTCurrentWord = new ArrayList<String>();
    	//mAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.customlist);
    	//mAdapter = new CustomListHomeActivity(ActivityHome.this, getInfoListHomeActivity());
    	showWordlist();
    	Log.i(MAIN_TAG, "vocadict_edit_search.requestFocus()");
    	vocadict_edit_search.requestFocus();
    	Log.i(MAIN_TAG, "mHandler = new Handler()");
    	mHandler = new Handler();
    	Log.i(MAIN_TAG, "mUpdateTimeTask = new Runnable()");
    	mUpdateTimeTask = new Runnable()
    	{
    		public void run()
    		{
    			Log.i(MAIN_TAG, "update word list now");
    			vocadict_edit_search.setEnabled(false);
    			showWordlist();
    			vocadict_edit_search.setEnabled(true);
    		}
    	};
    	Log.i(MAIN_TAG, "finish update word list");
    	vocadict_list.setOnItemClickListener(new AdapterView.OnItemClickListener() 
    	{
    		public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
    		{
    			
	    		imm.hideSoftInputFromWindow(vocadict_edit_search.getWindowToken(), 0);
	    		Intent i = new Intent(v.getContext(), ContentView.class);
	    		//i.putExtra("word", mAdapter.getItem(arg2));
	    		InfoListHomeActivity info = arraylist.get(position);
	    		i.putExtra("word", info.getWord());
	    		i.putExtra("id",mLSTCurrentWordId.get(position));
	    		i.putExtra("db", mDBFile.fileName);
	    		i.putExtra("dbName",mDBFile.dictionaryName);
	    		i.putExtra("style", mDBFile.style);
	    		i.putExtra("sourcesound", mDBFile.sourceLanguage);
	            startActivity(i);
				
    		}
		});
    	vocadict_edit_search.addTextChangedListener(new TextWatcher()
    	{ 
    		public void afterTextChanged(Editable s) 
    		{
                mHandler.removeCallbacks(mUpdateTimeTask);
                mHandler.postDelayed(mUpdateTimeTask, mWaitingTime*1000);
    		}
    		public void beforeTextChanged(CharSequence s, int start, int count, int after) 
    		{;} 
    	    public void onTextChanged(CharSequence s, int start, int before, int count) 
    		{;}
    	});
    	vocadict_btn_go.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(vocadict_edit_search.getText().toString().trim().equals(""))
				{
					
				}
				else
				{
					imm.hideSoftInputFromWindow(vocadict_edit_search.getWindowToken(), 0);
	    			Intent i = new Intent(v.getContext(), ContentView.class);
	    			i.putExtra("word", vocadict_edit_search.getText().toString());
	    			i.putExtra("db", mDBFile.fileName);
	    			i.putExtra("dbName",mDBFile.dictionaryName);
	    			i.putExtra("style", mDBFile.style);
	    			i.putExtra("sourcesound", mDBFile.sourceLanguage);
	                startActivity(i);
				}
			}
		});
    	vocadict_btn_add.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				String word = vocadict_edit_search.getText().toString();
				if(word.equals(""))
				{
					
				}
				else
				{
					arrayVocabulary = new ArrayList<InfoVocabulary>();
					arrayVocabulary = mVocabularySQLiteHelper.viewAllVocabulary();
					if(arrayVocabulary.size() < 1)
					{
						Intent mIntent = new Intent(ActivityHome.this, Vocabulary.class);
						startActivity(mIntent);
					}
					else
					{
						if(arrayVocabulary.size() == 1)
						{
							InfoVocabulary infoTable = arrayVocabulary.get(0);
							ArrayList<InfoVocabularyContent> mArarayVocabularyContent = mVocabularySQLiteHelper.viewAllVocabularyContent(infoTable.getName_table_vocabulary_content());
							int check = 0;
							for(int i=0; i< mArarayVocabularyContent.size(); i++)
							{
								InfoVocabularyContent mInfoVocabularyContent = mArarayVocabularyContent.get(i);
								if(word.equals(mInfoVocabularyContent.getWord()))
								{
									check = 1;
								}
							}
							if(check == 1)
							{
								Toast.makeText(getBaseContext(), word+getString(R.string.has_existed_in_list), Toast.LENGTH_SHORT).show();
							}
							else
							{
								//Check word is exist
								Uri uri = Uri.parse("content://hanelsoft.vn.dictionaylearn.model.common.VocadictProvider/dict/" + mDBFile.fileName + "/contentWord/" + word);
								//result = managedQuery(uri,null,null,null,null);
								result = getContentResolver().query(uri,null,null,null,null);
								int mCurrentWordId;
								String mCurrentWord;
								String mCurrentContent;
						        if (result != null && result.getCount() > 0)
						        {
						        	result.moveToFirst();
						        	mCurrentWordId = result.getInt(result.getColumnIndex("id"));
						        	mCurrentWord = result.getString(result.getColumnIndex("word"));
						        	mCurrentContent = result.getString(result.getColumnIndex("content"));
						        	mVocabularySQLiteHelper.addTableVocabularyContent(infoTable.getName_table_vocabulary_content(), String.valueOf(mCurrentWordId), mCurrentWord, mCurrentContent);
						        	Toast.makeText(getBaseContext(), getString(R.string.add_successful), Toast.LENGTH_SHORT).show();
						        }
						        else
						        {
						        	Toast.makeText(getBaseContext(), word+getString(R.string.is_not_exist), Toast.LENGTH_SHORT).show();
						        }
							}
						}
						else
						{
							LayoutInflater factory = LayoutInflater.from(ActivityHome.this);
					    	View view = factory.inflate(R.layout.dictionary_show, null);
					    	ScrollView mScrollView = (ScrollView)view.findViewById(R.id.dictionary_show_dictionary);
					    	final RadioGroup mRadioGroup = new RadioGroup(ActivityHome.this);
					    	mRadioGroup.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.FILL_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT));
					    	mRadioGroup.setOrientation(RadioGroup.VERTICAL);
					    	//
					    	for(int i=0; i<arrayVocabulary.size(); i++)
					    	{
					    		RadioButton mRadioButton = new RadioButton(ActivityHome.this);
					    		mRadioButton.setId(VIEW_RADIO_ID + i);
					    		infoGetVocabulary = arrayVocabulary.get(i);
					    		mRadioButton.setText(infoGetVocabulary.getName());
					    		mRadioButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
					    		mRadioGroup.addView(mRadioButton, i);
					    		if (arrayVocabulary != null)
					            {
					            	mRadioGroup.check(VIEW_RADIO_ID + i);
					            }
					    	}
					    	mScrollView.addView(mRadioGroup);
					    	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityHome.this);
					    	alertDialogBuilder.setView(view);
					    	alertDialogBuilder.setTitle(R.string.select_list_vocabulary);
					    	alertDialogBuilder.setIcon(R.drawable.icon);
					    	alertDialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					            @Override
					            public void onCancel(DialogInterface dialog) {
					                finish();
					            }
					        }).setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
								@Override
					            public void onClick(DialogInterface dialog, int which) {
					        		int selectedIndex = mRadioGroup.getCheckedRadioButtonId();
					        		if (selectedIndex < 0)
					        		{
					        			selectedIndex = 0;
					        		}
					        		infoGetVocabulary = arrayVocabulary.get(selectedIndex - VIEW_RADIO_ID);
					        		//String nameTableVocabulary = infoGetVocabulary.getName_table_vocabulary_content();
					        		String word = vocadict_edit_search.getText().toString();
									InfoVocabulary infoTable = arrayVocabulary.get(selectedIndex - VIEW_RADIO_ID);
									ArrayList<InfoVocabularyContent> mArarayVocabularyContent = mVocabularySQLiteHelper.viewAllVocabularyContent(infoTable.getName_table_vocabulary_content());
									int check = 0;
									for(int i=0; i< mArarayVocabularyContent.size(); i++)
									{
										InfoVocabularyContent mInfoVocabularyContent = mArarayVocabularyContent.get(i);
										if(word.equals(mInfoVocabularyContent.getWord()))
										{
											check = 1;
										}
									}
									if(check == 1)
									{
										Toast.makeText(getBaseContext(), word+getString(R.string.has_existed_in_list), Toast.LENGTH_SHORT).show();
									}
									else
									{
										//Check word is exist
										Uri uri = Uri.parse("content://hanelsoft.vn.dictionaylearn.model.common.VocadictProvider/dict/" + mDBFile.fileName + "/contentWord/" + word);
										//result = managedQuery(uri,null,null,null,null);
										result = getContentResolver().query(uri,null,null,null,null);
										int mCurrentWordId;
										String mCurrentWord;
										String mCurrentContent;
								        if (result != null && result.getCount() > 0)
								        {
								        	result.moveToFirst();
								        	mCurrentWordId = result.getInt(result.getColumnIndex("id"));
								        	mCurrentWord = result.getString(result.getColumnIndex("word"));
								        	mCurrentContent = result.getString(result.getColumnIndex("content"));
								        	mVocabularySQLiteHelper.addTableVocabularyContent(infoTable.getName_table_vocabulary_content(), String.valueOf(mCurrentWordId), mCurrentWord, mCurrentContent);
								        	Toast.makeText(getBaseContext(), getString(R.string.add_successful), Toast.LENGTH_SHORT).show();
								        }
								        else
								        {
								        	Toast.makeText(getBaseContext(), word+getString(R.string.is_not_exist), Toast.LENGTH_SHORT).show();
								        }
									}
					            }
					        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
								}
							});
					    	Dialog dialog = alertDialogBuilder.create();
					        dialog.show();
						}
					}
				}
			}
		});
    	//
    	String nameDictionary = mDBFile.dictionaryName;
    	Log.i(MAIN_TAG, "nameDictionary = "+nameDictionary);
    	if(nameDictionary.equals("Từ điển Việt Anh"))
    	{
    		Log.i(MAIN_TAG, "nameDictionary = getString(R.string.vietnamesetoenglish)");
    		nameDictionary = getString(R.string.vietnamesetoenglish);
    	}
    	else
    	{
    		if(nameDictionary.equals("Từ điển Anh Việt"))
        	{
    			Log.i(MAIN_TAG, "nameDictionary = getString(R.string.englishtovietnamese);");
        		nameDictionary = getString(R.string.englishtovietnamese);
        	}
    	}
    	Log.i(MAIN_TAG, "vocadict_show_dictionary.setText(nameDictionary)");
    	vocadict_show_dictionary.setText(nameDictionary);
    	Log.i(MAIN_TAG, "finish vocadict_show_dictionary.setText(nameDictionary)");
        vocadict_show_dictionary.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDictionary();
			}
		});
    }

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_home, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.menu_setting:
		{
			Intent setting = new Intent(this, Setting.class);
			startActivity(setting);
		}break;
		case R.id.menu_vocabulary:
		{
			Intent mIntent = new Intent(this, Vocabulary.class);
			startActivity(mIntent);
		}break;
		case R.id.menu_dictionary:
		{
			showDictionary();
		}break;
		case R.id.menu_about:
		{
			setContentView(R.layout.about);
			WebView wvInfo = (WebView) findViewById(R.id.about_Info);
			wvInfo.loadUrl("file:///android_asset/about.html");
			Button btnOkAbout = (Button) findViewById(R.id.about_btnOK);
	        btnOkAbout.setOnClickListener(new OnClickListener()
	        {
	        	public void onClick(View v)
	        	{
	                setContentView(R.layout.activity_home);
	                if (mDBList.items.size() > 0)
	                {
	                    menuMain();
	                }
	        	}
	        });
		}break;
		case R.id.menu_help:
		{
			setContentView(R.layout.about);
			WebView wvInfo = (WebView) findViewById(R.id.about_Info);
			wvInfo.loadUrl("file:///android_asset/help.html");
			Button btnOkAbout = (Button) findViewById(R.id.about_btnOK);
	        btnOkAbout.setOnClickListener(new OnClickListener()
	        {
	        	public void onClick(View v)
	        	{
	                setContentView(R.layout.activity_home);
	                if (mDBList.items.size() > 0)
	                {
	                    menuMain();
	                }
	        	}
	        });
		}break;
		case R.id.menu_history:
		{
			Intent history = new Intent(this, History.class);
			startActivity(history);
		}break;
    	}
    	return super.onOptionsItemSelected(item);
    }

}
